# Copyright 2017 The dev Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

declare -gr dev_global_ssh_key="$HOME/.ssh/$dev_conf_ssh_key"

dev_import dev file
dev_import dev io

#
# Usage:
#     dev_scp <user-host> <command>
#
dev_scp() {
    declare cmd="scp -i $dev_global_ssh_key -o StrictHostKeyChecking=no $@"
    dev_verbose "$cmd"
    $cmd
}

#
# Usage:
#     dev_ssh <user-host> <command>
#
dev_ssh() {
    declare cmd="ssh -i $dev_global_ssh_key -o StrictHostKeyChecking=no $@"
    dev_verbose "$cmd"
    $cmd
}

#
# Usage:
#     dev_download <url> [fname]
#
dev_download() {
    [ -z $1 ] && return 1
    [ -z $2 ] && local fname=$(basename $1) || local fname=$2
    [ -z $fname ] && return 1

    declare opts fp=$dev_global_wkdir/var/downloads/$fname tfp=$dev_global_wkdir/var/tmp/$fname

    if [[ -f $fp ]]; then
        dev_verbose "File exists: $fp"
        return 0
    fi

    # Delete temp file
    [[ -f $tfp ]] && rm -f $tfp

    [ ! -z $dev_conf_proxy ] && opts="-k -x $dev_conf_proxy"

    declare cmd="curl $opts -L $1 -o $tfp"

    dev_verbose "$cmd"

    # Delete the temporary files generated by the download
    if ! $cmd && [ -f $tfp ]; then
        rm -f $tfp
    fi

    if [[ -f $tfp ]]; then
        cp $tfp $fp && rm -f $tfp
    fi
}

#
# Usage:
#     dev_extra <fname> <extra-dir> <strip-components>
#
dev_extra() {
    [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] && echo "Usage: dev_extra <fname> <strip-components>" >&2 && return 1
    declare fp=$dev_global_wkdir/var/downloads/$1 sp=$dev_global_wkdir/src/$2
    [ ! -z $dev_global_wkdir ] && [ ! -z "$2" ] && [ -d $sp ] && rm -rf $sp
    mkdir -p $sp
    declare cmd="tar --strip-components $3 -xzf $fp -C $sp"
    dev_verbose "$cmd"
    $cmd
}

#
# Download and extract to src/<dir>.
# Usage:
#     dev_dextra <url> <fname> <strip-components>
#
#     example:
#         Download to var/downloads/nginx-1.2.0.tar.gz
#         Extra to src/nginx-1.2.0
#         dev_dextra http://xxx.com/v1.2.0.tar.gz nginx-1.2.0.tar.gz 1
#
dev_download_and_extra() {
    [[ $# -lt 3 ]] && echo "Usage: dev_dextra <url> <fname> <strip-components>" >&2 && return 1
    declare url="$1" fname="$2"
    declare exdir="$(dev_file_basename $fname)"
    dev_download $url $fname
    dev_extra $fname $exdir $3
}

